package cn.airfei.netty.nio.groupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @description:
 * @author: air
 * @create: 2021-01-15 09:52
 */
public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private static final int PORT=6667;

    // 初始化工作
    public GroupChatServer() {
        try {
            selector=Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            // 绑定端口
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置为非阻塞模式
            serverSocketChannel.configureBlocking(false);
            // 将serverSocketChannel 注册到selector上
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 监听
    public void listen(){
        try {
            while (true){
                int count=selector.select();
                if (count>0){
                    // 有事件处理
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey selectionKey = iterator.next();
                        if (selectionKey.isAcceptable()){
                            SocketChannel accept = serverSocketChannel.accept();
                            accept.configureBlocking(false);
                            accept.register(selector,SelectionKey.OP_READ);
                            System.out.println(accept.getRemoteAddress()+" 上线");
                        }
                        if (selectionKey.isReadable()){
                            // read事件
                            readData(selectionKey);
                        }

                        // 删除当前动作
                        iterator.remove();

                    }
                }else {
                    System.out.println("等待...");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void readData(SelectionKey selectionKey){
        SocketChannel socketChannel=null;

        try {
            socketChannel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
            int count = socketChannel.read(byteBuffer);
            if (count>0){
                // 把缓存区的数据转成字符串
                String s = new String(byteBuffer.array());
                System.out.println("form 客户端: "+ s);
                // 向其他客户端转发消息
                sendMsgToOtherClient(s,socketChannel);
            }

        } catch (IOException e) {
            try {
                System.out.println(socketChannel.getRemoteAddress()+" 离线了");
                // 取消注册
                selectionKey.cancel();
                // 关闭通道
                socketChannel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            e.printStackTrace();
        }

    }

    private void sendMsgToOtherClient(String msg,SocketChannel selfChannel) throws IOException {
        System.out.println("服务器转发消息中.....");
        for (SelectionKey key:selector.keys()){
            Channel targetChannel = key.channel();
            // 排除自己
            if (targetChannel instanceof SocketChannel && targetChannel !=selfChannel){
                SocketChannel dest= (SocketChannel) targetChannel;
                ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                dest.write(wrap);
            }
        }

    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }

}
